# views.py
from datetime import datetime

from django.http import HttpResponse,JsonResponse,StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone

from aiModels import get_prompt
from coreServices.models import ChatRecord
# import datetime
from coreServices.dao.PointsRecordDao import consumePoints

from filters.Login_filter import login_filter
import json
import traceback

import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Create your views here.
# 用于获取AI的答复
@csrf_exempt
def get_answers(request):
    # 判断有没有登录
    if request.session.get('user_id') is None:
        logging.warning('用户未登录，请求被拒绝')
        return JsonResponse({'error': '请先登录'}, status=401)

    # 判断是否为 POST 请求
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            input_text = data.get('input_text')

            # 检查输入是否为空
            if not input_text:
                logging.warning('用户输入内容为空，请求被拒绝')
                return JsonResponse({'error': '输入内容不能为空'}, status=400)

            # 初始化会话
            session = request.session.get('chat_record')
            logging.info(f"开始获取 AI 答复，输入内容：{input_text}")
            result_generator, session = get_prompt(user_prompt=input_text, session=session)
            request.session['chat_record'] = session

            logging.info(f"成功获取答复生成器，正在提问中：{input_text}")

            # 检查是否成功获取答复
            if result_generator is not None:
                # 消耗积分
                consumePoints(request.session['user_id'], 2)
                logging.info(f"为用户 {request.session['user_id']} 消耗 2 积分")

                full_reply = ""
                try:
                    for chunk in result_generator:
                        full_reply += chunk
                except Exception as e:
                    logging.error(f"生成答复过程中出现错误：{str(e)}", exc_info=True)
                    return JsonResponse({'error': '生成答复时发生错误'}, status=500)

                # 准备聊天记录数据
                chat_data = {
                    "data":{
                    "userId_id": request.session['user_id'],
                    "chat_content": input_text,
                    "create_time": timezone.now().strftime('%Y-%m-%d %H:%M:%S'),
                    "reply_content": full_reply,
                    "is_delete": False
                }
                }

                # 保存聊天记录到数据库
                try:
                    ChatRecord.objects.create(**chat_data)
                    logging.info("聊天记录成功保存到数据库")
                except Exception as e:
                    logging.error(f"保存聊天记录到数据库时出现错误：{str(e)}", exc_info=True)

                # 返回完整的 JSON 响应
                return JsonResponse(chat_data, status=200)
            else:
                logging.warning('无法生成答复，返回错误信息')
                # 如果无法生成答复，返回错误信息
                return JsonResponse({'error': '很抱歉，我暂时无法理解您的问题。'}, status=500)

        except json.JSONDecodeError:
            logging.warning('无效的 JSON 输入，请求被拒绝')
            return JsonResponse({'error': '无效的 JSON 输入'}, status=400)
        except Exception as e:
            # 捕获异常并返回错误信息
            logging.error(f'服务器内部错误: {str(e)}', exc_info=True)
            traceback.print_exc()  # 打印完整的堆栈跟踪信息
            return JsonResponse({'error': f'服务器内部错误: {str(e)}'}, status=500)
    else:
        logging.warning('请求方法不支持，返回错误信息')
        # 如果不是 POST 请求，返回错误信息
        return JsonResponse({'error': '请求方法不支持'}, status=405)



# 获取聊天记录
@csrf_exempt
def get_chat_record(request):
    # 判断有没有登录
    if request.session.get('user_id') is None:
        return JsonResponse({'error': '请先登录'}, status=401)

    if request.method == 'GET':
        # 从数据库中获取聊天记录
        chat_records = ChatRecord.objects.filter(userId=request.session['user_id']).values()

        # 将 QuerySet 转换为列表
        chat_records_list = list(chat_records)
        # 将 datetime 对象转换为字符串
        for record in chat_records_list:
            if 'create_time' in record:
                record['create_time'] = record['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        result = {
            'chat_record': chat_records_list
        }
        import json
        response_json = json.dumps(result)

        return HttpResponse(response_json, content_type='application/json')
    else:
        return HttpResponse('{"error": "请求错误"}', content_type='application/json')


# 删除聊天记录的方法
@csrf_exempt
def delete_chat_record(request):
    # 判断有没有登录
    if request.session.get('user_id') is None:
        return JsonResponse({'error': '请先登录'}, status=401)
    # 判断是否为post请求
    if request.method != 'POST':
        return HttpResponse('{"error": "请求方法错误"}', content_type='application/json')
    # 获取请求参数
    record_id = request.POST.get('record_id')
    if not record_id:
        return HttpResponse('{"error": "record_id 不能为空"}', content_type='application/json')
    try:
        # 删除聊天记录
        deleted_count = ChatRecord.objects.filter(id=record_id, userId=request.session['user_id']).delete()[0]
        if deleted_count > 0:
            return HttpResponse('{"success": true}', content_type='application/json')
        else:
            return HttpResponse('{"error": "聊天记录不存在"}', content_type='application/json')
    except Exception as e:
        return HttpResponse(f'{{"error": "{str(e)}"}}', content_type='application/json')